<?php

namespace app\middleware;

use app\Request;

class PlugMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        $path = $request->pathinfo();
        $paths = explode('/',$path);
        if (count($paths) > 2) {
            list($model, $controller, $action) = $paths;
            if (in_array($model, ['admin', 'api'])) {
                $classFile = app_path() . $model . '/controller/' . ucfirst($controller) . '.php';
                if (!file_exists($classFile)) {
                    list($author, $plugName, $controller) = explode('_', $controller);
                    app('http')->name('plug');
                    $plugControllerPath = 'app\\plug\\' . $model . '\\' . $author . '_' . $plugName . '\\' . ucfirst($controller);
                    if (class_exists($plugControllerPath)) {
                        $controller = new $plugControllerPath(app());
                        if (method_exists($controller, $action)) {
                            $res = $controller->$action();
                            if ($res) {
                                return response($res, 200, [], 'json');
                            } else {
                                return response();
                            }
                        }
                    }
                }
            }
        }
        return $next($request);
    }
}
